package io.github.junxworks.qt.modules.mm.engine.handlers;

import java.util.stream.DoubleStream;

import org.springframework.stereotype.Component;

import io.github.junxworks.junx.event.EventChannel;
import io.github.junxworks.junx.event.EventChannelHandler;
import io.github.junxworks.junx.event.EventContext;
import io.github.junxworks.qt.config.Params;
import io.github.junxworks.qt.config.Topics;
import io.github.junxworks.qt.modules.mm.engine.DataContext;
import io.github.junxworks.qt.modules.mm.engine.ExeContext;
import io.github.junxworks.qt.modules.mm.entity.RModelResult;

@Component
public class ModelHandler implements EventChannelHandler {

	@Override
	public void handleEvent(EventContext event, EventChannel channel) throws Exception {
		DataContext data = event.getData(DataContext.class, Params.DATA_CONTEXT);
		ExeContext exeContext = data.getExeContext();
		try {
			if (!data.isDone()) {
				String column = data.getKey().getColumn();
				String key = data.getKey().getValue();
				String tradeDate = exeContext.getTradeDate();
				exeContext.getModelNos().forEach(m -> {
					double score = exeContext.getExpressionMap().get(m).stream().flatMapToDouble(e -> {
						return DoubleStream.of(Double.valueOf(String.valueOf(exeContext.getExpressionResult(e.getExpName() + "-" + key))));
					}).sum();
					if (score > 0) {
						RModelResult mr = new RModelResult();
						mr.setKeyName(column);
						mr.setKeyValue(key);
						mr.setName(exeContext.getModelMap().get(m).getModelName());
						mr.setValue(score);
						mr.setTradeDate(tradeDate);
						EventContext ctx = new EventContext(Topics.STORE_MODEL_RES);
						ctx.setData(Params.PARAM_STORE_OBJ, mr);
						try {
							channel.publish(Topics.STORE_MODEL_RES, ctx);
						} catch (Exception e1) {
						}
					}
				});
				data.done();
			}
		} catch (Throwable e) {
			data.setException(e);
		}
	}

}
